package cn.z2huo.knowledge.streamapi.parallel;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *
 * @author z2huo
 */
class Test {

    public static void main(String[] args) {

        Test test = new Test();
        List<Integer> initList = test.init();

        long start, end;

        start = System.currentTimeMillis();
        initList.parallelStream().forEach(x -> {
            ThreadLocalRandom current = ThreadLocalRandom.current();
            int i = current.nextInt(10, 60);
            System.out.println("thread id is " + Thread.currentThread().threadId() + " process " + x + ", sleep " + i + " ms");
            try {
                TimeUnit.MILLISECONDS.sleep(i);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        end = System.currentTimeMillis();
        System.out.println("=============================================");
        System.out.println("parallelStream: " + (end - start));
        System.out.println("=============================================");

        start = System.currentTimeMillis();
        initList.forEach(x -> {
            ThreadLocalRandom current = ThreadLocalRandom.current();
            int i = current.nextInt(10, 60);
            System.out.println("thread id is " + Thread.currentThread().threadId() + " process " + x + ", sleep " + i + " ms");
            try {
                TimeUnit.MILLISECONDS.sleep(i);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        end = System.currentTimeMillis();
        System.out.println("=============================================");
        System.out.println("stream: " + (end - start));
        System.out.println("=============================================");
    }

    List<Integer> init() {
        List<Integer> arrayList = new ArrayList<>(500);
        for (int i = 0; i < 500; i++) {
            arrayList.add(i);
        }
        return arrayList;
    }

}
